<template>
  <div class="account-setting">
    <div class="header">
      <div class="title">我的账户</div>
      <div>
        <el-button
          v-show="!isEdit"
          :size="size"
          icon="el-icon-setting"
          @click="dialogVisible = true"
          >修改密码</el-button
        >
        <el-button
          v-show="!isEdit"
          type="primary"
          :size="size"
          icon="el-icon-edit"
          @click="isEdit = true"
          >编辑信息</el-button
        >
      </div>
    </div>
    <div class="form-container">
      <el-form
        class="form"
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="80px"
        :size="size"
      >
        <el-form-item prop="username" label="用户名">
          <div v-if="!isEdit" class="text">{{ userInfo.username }}</div>
          <el-input
            v-else
            v-model="ruleForm.username"
            placeholder="请输入用户名"
            :disabled="!isEdit"
          />
        </el-form-item>
        <el-form-item prop="email" label="邮箱">
          <div v-if="!isEdit" class="text">{{ userInfo.email }}</div>
          <el-input
            v-else
            type="email"
            v-model="ruleForm.email"
            placeholder="请输入邮箱"
          />
        </el-form-item>
        <el-form-item prop="phone" label="手机号">
          <div v-if="!isEdit" class="text">{{ userInfo.phone }}</div>
          <el-input
            v-else
            type="phone"
            v-model="ruleForm.phone"
            placeholder="请输入手机号"
          />
        </el-form-item>
        <el-form-item>
          <el-button @click="reset" v-show="isEdit"> 取消 </el-button>
          <el-button
            class="changePwdBtn"
            type="primary"
            @click="submit"
            v-show="isEdit"
          >
            确认
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-dialog
      title="修改密码"
      :visible.sync="dialogVisible"
      class="address-dialog"
      :width="dialogWidth"
      :before-close="handleClose"
    >
      <el-form
        class="form"
        :model="dialogForm"
        :rules="dialogRules"
        ref="dialogFormRef"
        label-width="auto"
        :size="size"
      >
        <el-form-item prop="oldPassword" label="旧密码">
          <el-input
            type="password"
            v-model="dialogForm.oldPassword"
            placeholder="请输入旧密码"
            show-password
          />
        </el-form-item>
        <el-form-item prop="newPassword" label="新密码">
          <el-input
            type="password"
            v-model="dialogForm.newPassword"
            placeholder="请输入新密码"
            show-password
          />
        </el-form-item>
        <el-form-item prop="confirmPassword" label="确认密码">
          <el-input
            type="password"
            v-model="dialogForm.confirmPassword"
            placeholder="请确认密码"
            show-password
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button :size="size" @click="handleClose">取 消</el-button>
        <el-button :size="size" type="primary" @click="editPassword"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "ChangePassword",
  data() {
    let phoneReg = /^1[3456789]\d{9}$/;
    let emailReg =
      /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
    let Phone = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("手机号不能为空"));
      } else if (!phoneReg.test(value)) {
        callback(new Error("请输入有效的手机号码"));
      } else {
        callback();
      }
    };
    let Email = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("邮箱不能为空"));
      } else if (!emailReg.test(value)) {
        callback(new Error("请输入正确的邮箱"));
      } else {
        callback();
      }
    };
    let password = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入新密码"));
      } else if (value.length < 8 || value.length > 20) {
        callback(new Error("密码的长度必须为8~20位"));
      } else {
        callback();
      }
    };
    let confirmPassword = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请确认密码"));
      } else if (value !== this.dialogForm.newPassword) {
        callback(new Error("两次输入密码不一致"));
      } else {
        callback();
      }
    };
    return {
      size: "small",
      isEdit: false,
      userInfo: {},
      ruleForm: {
        password: "",
        confirmPassword: "",
      },
      rules: {
        phone: [{ required: true, validator: Phone, trigger: "blur" }],
        username: [
          { required: true, message: "昵称不能为空", trigger: "blur" },
        ],
        email: [{ required: true, validator: Email, trigger: "blur" }],
      },
      dialogVisible: false,
      screenWidth: 0,
      dialogWidth: "600px",
      dialogForm: {
        oldPassword: "",
        newPassword: "",
        confirmPassword: "",
      },
      dialogRules: {
        oldPassword: [
          { required: true, message: "请输入旧密码", trigger: "blur" },
        ],
        newPassword: [{ validator: password, trigger: "blur", required: true }],
        confirmPassword: [
          { validator: confirmPassword, trigger: "blur", required: true },
        ],
      },
    };
  },
  methods: {
    getInfo() {
      let url = "/admin/user/get/" + this.$store.state.user.userId;
      this.$axios.get(url).then((response) => {
        if (response && response.data.code === 200) {
          let data = response.data.data;
          this.userInfo = response.data.data;
          this.$set(this.ruleForm, "username", data.username);
          this.$set(this.ruleForm, "email", data.email);
          this.$set(this.ruleForm, "phone", data.phone);
        } else {
          this.$message.error("查找用户信息失败!");
        }
      });
    },
    submit() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.$axios
            .put("/admin/user/update", {
              email: this.ruleForm.email,
              phone: this.ruleForm.phone,
              username: this.ruleForm.username,
            })
            .then((response) => {
              if (response.data.code === 200) {
                this.$message.success("修改成功");
                this.isEdit = false;
                this.getInfo();
              } else {
                this.$message.error(response.data.message);
              }
            })
            .catch((failResponse) => {});
        }
      });
    },
    reset() {
      this.isEdit = false;
      this.$set(this.ruleForm, "username", this.userInfo.username);
      this.$set(this.ruleForm, "email", this.userInfo.email);
      this.$set(this.ruleForm, "phone", this.userInfo.phone);
      this.$refs.ruleForm.clearValidate();
    },
    handleClose() {
      this.dialogVisible = false;
      this.$set(this.dialogForm, "oldPassword", "");
      this.$set(this.dialogForm, "newPassword", "");
      this.$set(this.dialogForm, "confirmPassword", "");
      this.$refs.dialogFormRef.clearValidate();
    },
    editPassword() {
      this.$refs.dialogFormRef.validate((valid) => {
        if (valid) {
          this.$axios
            .post("/user/profile/changePwd", {
              oldPassword: this.dialogForm.oldPassword,
              newPassword: this.dialogForm.newPassword,
              confirmPassword: this.dialogForm.confirmPassword,
            })
            .then((response) => {
              if (response.data.code === 200) {
                this.$message.success("修改成功");
                this.dialogVisible = false;
              } else {
                this.$message.error(response.data.message);
              }
            });
        }
      });
    },
  },
  mounted() {
    this.getInfo();
    this.screenWidth = document.body.clientWidth;
    window.onresize = () => {
      this.screenWidth = document.body.clientWidth;
    };
  },
  watch: {
    screenWidth: {
      handler(val) {
        if (val < 768) {
          this.dialogWidth = "80%";
        } else if (val < 480) {
          this.dialogWidth = "90%";
        } else {
          this.dialogWidth = "600px";
        }
      },
      immediate: true,
      deep: true,
    },
  },
};
</script>

<style scoped lang="scss">
.account-setting {
  padding: 20px;
  width: 100%;

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;

    .title {
      font-size: 1.2em;
      font-weight: bold;
      text-align: left;
    }
  }

  .form-container {
    margin-top: 40px;

    .form {
      max-width: 500px;
      margin: 0 auto;
    }
  }
}

.text {
  text-align: left;
  padding-left: 15px;
}

.address-dialog {
  text-align: left;
}
</style>